<script setup lang="ts">
import {ref, reactive,onMounted,onActivated, onDeactivated } from "vue";
import { useRouter ,onBeforeRouteLeave} from "vue-router";
const router = useRouter()
const jump = () => {
    router.push('/work/demo1')
}
const arrList = () => {
    const arr = reactive<number[]>([])
    for (let i = 0; i < 100; i++) {
        arr.push(i);
    }

    let curScrollTop = ref<any>(null)

    // 保存滚动的函数
    const saveScrollPosition = () => {
        if (curScrollTop.value) {
            const scrollPosition = curScrollTop.value.scrollTop;
            console.log('保存路由的位置', scrollPosition);
            sessionStorage.setItem('my-scroll-position', scrollPosition.toString());
    }
};

    return { arr,curScrollTop,saveScrollPosition }
}
const {arr,curScrollTop ,saveScrollPosition} = arrList()

onMounted(() => {  
    // sessionStorage.removeItem('my-scroll-position');
    console.log('HomeMounted');
})
 
onActivated(() => {
    const savedPosition = sessionStorage.getItem('my-scroll-position');
    if (savedPosition !== null && curScrollTop.value) {
        curScrollTop.value.scrollTop = parseInt(savedPosition);
        console.log(curScrollTop.value.scrollTop,'激活top');
    }
});

// 路由离开前保存滚动位置
onBeforeRouteLeave(() => {
    saveScrollPosition();
});

onDeactivated(() => {
    // saveScrollPosition();
});
</script>
<template>
    <div class="home-wrap">
        <div class="box" @click="jump">跳转demo1</div>
        <div class="arr-box"  ref="curScrollTop">
            <div class="item" v-for="(item,index) in arr" :key="index">{{ item }}</div>
        </div>
    </div>    
</template>


<style scoped lang="less">
.home-wrap{
    width:100%;
    height: 100%;
    font-size:32px;
    .box{
        width: 100px;
        height: 80px;
        background-color: #eee;
    }
    .arr-box{
        width: 100%;
        height: 100%;
        height: calc(100vh - 180px);
        background-color: #bfa;
        overflow-y: auto;

        .item{
            width: 100%;
            height: 50px;
        }
    }
}
</style>
